package services

import (
	"gorm.io/gorm"
	"rookie-wrapping/rpc/global"
	"rookie-wrapping/rpc/models/dao"
)

func CreateUser(user dao.User) error {
	return global.Db.Create(&user).Error
}

func CreatePackage(p dao.Package) error {
	return global.Db.Create(&p).Error
}

func PackageList(Destination string, page, pageSize int) (list []*dao.Package, err error) {
	err = global.Db.Where("destination like ?", "%"+Destination+"%").Order("weight").Scopes(Paginate(page, pageSize)).Find(&list).Error
	return list, err
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
